package com.tm.action.feixin;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.mime.Header;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.util.ObjectUtils;

import sun.net.www.http.HttpClient;

import com.google.gson.Gson;
import com.tm.model.BaseModel;
import com.tm.util.Constants;
import com.tm.util.CookieUtils;
import com.tm.util.SLLWrapper;

public class BaseAction {
	
	public int version = 0;

	public synchronized String nextRequestVersion() {
		version++;
		return String.valueOf(version);
	}
	
    public String executeCallBack (HttpCallBack callBack) {
        return callBack.execute();
    }
    
	public HttpPost getPostMethod (String URL) {
		HttpPost httpPost = new HttpPost(URL);
		return httpPost;
	}
	
	public String getCookiesString(javax.servlet.http.Cookie cookies[]) {
		StringBuilder stringBuilder = new StringBuilder();
		if (cookies != null) {
			for (javax.servlet.http.Cookie cookie : cookies) {
				if (cookie.getName().equals("JSESSIONID")) {
					continue;
				}
				stringBuilder.append(cookie.getName());
				stringBuilder.append("=");
				stringBuilder.append(cookie.getValue());
				stringBuilder.append("; ");
			}
		}
		return stringBuilder.toString();
	}
    
	public HttpPost setHeaders(HttpServletRequest request, HttpPost postMethod) {
		postMethod.setHeader("Accept", "application/json, text/javascript, */*");
    	postMethod.setHeader("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
    	postMethod.setHeader("Accept-Encoding", "gzip,deflate,sdch");
    	postMethod.setHeader("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.4");
    	postMethod.setHeader("Connection", "keep-alive");
    	postMethod.setHeader("Cookie", getCookiesString(request.getCookies()) + 
    			"CmProvid=sh; WT_FPC=id=2828352cf40b6bc12281319953437283:lv=1358862747529:ss=1358862747529");
    	postMethod.setHeader("Content-Type", "application/x-www-form-urlencoded");
        postMethod.setHeader("Host", "webim.feixin.10086.cn");
        postMethod.setHeader("Origin", "https://webim.feixin.10086.cn");
        postMethod.setHeader("Referer", "https://webim.feixin.10086.cn/content/freeSms.htm?tabIndex=0");
        postMethod.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11");
        postMethod.setHeader("X-Requested-With", "XMLHttpRequest");
        
        return postMethod;
	}
	
    public String executePostMethod (DefaultHttpClient httpclient, HttpPost postMethod) {

    	org.apache.http.client.HttpClient client = SLLWrapper.wrapperClient(httpclient);
    	String returnMsg = null;
        try {
        	HttpResponse response = client.execute(postMethod);
            HttpEntity entity = response.getEntity();
            returnMsg = EntityUtils.toString(entity, Consts.UTF_8);
            System.out.println(returnMsg);
            
        } catch (ClientProtocolException e) {
	        e.printStackTrace();
        } catch (IOException e) {
	        e.printStackTrace();
        }
        
        return returnMsg;
    }
    
    public String executeSignIn(DefaultHttpClient httpclient, HttpServletResponse resp, HttpPost postMethod) 
    {
    	
        HttpResponse response;
        Gson gson = new Gson();
        
        try {

            response = httpclient.execute(postMethod);
            HttpEntity entity = response.getEntity();
            
            String returnMsg = EntityUtils.toString(entity);
            System.out.println(returnMsg);
            BaseModel msg = gson.fromJson(returnMsg, BaseModel.class);
            
            if (msg != null) {
            	if (msg.getRc() == Constants.STATUS_SUCCESS) {

                    List<Cookie> cookies = httpclient.getCookieStore().getCookies();
                    if (cookies.isEmpty()) {
                        return Constants.APPLICATION_ERROR;
                    } else {
                        for (int i = 0; i < cookies.size(); i++) {
                        	
                        	Cookie serverCookie = cookies.get(i);
                        	// write fetion cookie to client
                        	CookieUtils.addCookie(resp, serverCookie.getName(), serverCookie.getValue());
                        }
                        javax.servlet.http.Cookie clientCookie = new javax.servlet.http.Cookie(Constants.IS_COOKIES_ENABLE, "true");
                        resp.addCookie(clientCookie);
                		return Constants.SUCCESS;
                    }
            	} else if(msg.getRc() == Constants.STATUS_VALICATE) {
                	// 验证码
            		return Constants.APPLICATION_ERROR;
                }
            }
            
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Constants.APPLICATION_ERROR;
    }
    
    public String getViewByStatus (int status) {
    	
    	String view = Constants.APPLICATION_ERROR;
    	
    	if (status == Constants.STATUS_SUCCESS) {
    		view = Constants.SUCCESS;
    	}
    	
    	return view;
    }
}
